<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片内容区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 搜索与添加区域 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUsers">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区 -->
       <el-table :data="userlist" style="width: 100%" border stripe><!-- 不同列表列 -->
       <el-table-column type="index"></el-table-column>
      <el-table-column prop="username" label="姓名" width="180"></el-table-column>
      <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
      <el-table-column prop="mobile" label="电话" width="180"></el-table-column>
      <el-table-column prop="role_name" label="角色" width="180"></el-table-column>
      <el-table-column label="状态" width="180">
          <template slot-scope="scope">
              <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"><!-- 绑定数据使用作用域插槽 -->
              </el-switch>
          </template>
      </el-table-column>
      <el-table-column label="操作" width="180" min-width="180">
          <template slot-scope="scope"><!-- 接受来自作用域插槽的数据 -->
           <!--  {{scope.row}} -->
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button><!-- 修改按钮 -->
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserByid(scope.row.id)"></el-button><!-- 删除按钮 -->
          <!-- 分配角色按钮 -->
    <el-tooltip effect="dark" content="分配角色" placement="top-start" :enterable="false">
        <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRole(scope.row)"></el-button>
    </el-tooltip>
          </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 进行页面和页码的操作--> <!-- layout指定页面上存在哪些的布局结构 -->
     <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </el-card>
    <!-- 弹出框信息,添加用户 -->
<el-dialog title="添加用户" :visible.sync="adddialogVisible" width="50%" @close="closeAddDialog">
     <!-- 内容主体区域 -->
    <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
  <el-form-item label="用户名" prop="username">
    <el-input v-model="addForm.username"></el-input>
  </el-form-item>
   <el-form-item label="密码" prop="password"><!-- prop是校验规则 -->
    <el-input v-model="addForm.password" type="password"></el-input>
  </el-form-item>
   <el-form-item label="邮箱" prop="email">
    <el-input v-model="addForm.email"></el-input>
  </el-form-item>
   <el-form-item label="电话" prop="mobile">
    <el-input v-model="addForm.mobile"></el-input>
  </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer"><!-- 底部按钮区域 -->
    <el-button @click="adddialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUserdata">确 定</el-button>
    </span>
</el-dialog>
<!-- 修改用户弹框 -->
<el-dialog title="修改用户" :visible.sync="editdialogVisible"
 width="50%" @close="closeEditDialog">
 <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
  <el-form-item label="用户名">
    <el-input v-model="editForm.username" disabled></el-input>
  </el-form-item>
   <el-form-item label="邮箱" prop="email">
    <el-input v-model="editForm.email"></el-input>
  </el-form-item>
   <el-form-item label="电话" prop="mobile">
    <el-input v-model="editForm.mobile"></el-input>
  </el-form-item>
 </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editUserdata">确 定</el-button>
  </span>
</el-dialog>
<!-- 分配角色弹框 -->
<el-dialog
  title="分配角色"
  :visible.sync="setRolesdialogVisible"
  width="50%" @close="setRoleDialogClosed">
  <p>当前用户:{{userInfo.username}}</p>
  <p>当前角色:{{userInfo.role_name}}</p>
  <p>新的角色: <el-select v-model="selectedRoleId" placeholder="请选择">
    <el-option
      v-for="item in roleLists"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select></p>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRolesdialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>
<!-- 行为区域 -->
<script>
export default {
  data () {
    // 自定义手机号码和邮箱的校验规则
    var checkEmail = (rules, value, callback) => {
      /* 验证邮箱的正则表达式 */
      const regEmail = /^([a-zA-Z]|[0-9])(\w|-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/

      if (regEmail.test(value)) {
        return callback();
      }
      callback(new Error('请输入合法的邮箱!'));
    }
    /* 对电话的验证 */
    var checkMobile = (rules, value, callback) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return callback();
      }
      callback(new Error('请输入合法的电话号码!'));
    }

    return {
    // 控制分配角色的打开与关闭
      setRolesdialogVisible: false,
      // 定义get常见请求参数.请求数据时候使用的参数
      queryInfo: {
        query: '', /* 搜索关键字 */
        /* 当前的页数 */
        pagenum: 1,
        pagesize: 2
      },
      editForm: {}, // 修改用户数据时保存的数据
      userlist: [], // 用户数据保存
      userInfo: '', // 一行的用户数据
      total: 0,
      roleLists: [], // 角色列表数据
      selectedRoleId: '', // 当前选中的新的角色名称
      adddialogVisible: false, /* 控制添加用户对话框的显示与隐藏 */
      addForm: { // 添加的用户数据
        username: '',
        password: '',
        email: '',
        mobile: ''
      }, /* 指向添加用户的表单数据 */
      addFormRules: { /* 添加用户表单数据验证 */
        username: [
          { required: true, message: '请输入用户名！', trigger: 'blur' },
          { min: 3, max: 10, message: '用户名在3到10个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码！', trigger: 'blur' },
          { min: 6, max: 15, message: '密码在6到15个字符之间', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱！', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }/* 自定义校验合法性 */
        ],
        mobile: [
          { required: true, message: '请输入电话号码！', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 控制修改用户弹窗显示
      editdialogVisible: false,
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱！', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }/* 自定义校验合法性 */
        ],
        mobile: [
          { required: true, message: '请输入电话号码！', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      } // 修改用户数据校验部分
    };
  },
  created () {
    this.getUserList();
  },
  methods: {
    getUserList: async function () { /* 请求用户资料数据向服务端 */
      const { data: res } = await this.$http.get('users', { params: this.queryInfo });// 发起请求数据
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败!');
      }
      this.userlist = res.data.users;
      this.total = res.data.total;

      // console.log(res);
    },
    handleSizeChange: function (newSize) { /* 定义每页的条数 监听pagesize改变 */
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange: function (newPage) { /* 监听页码值改变的事件 */
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },
    /* 监听Switch状态的改变 */
    userStateChange: async function (userState) {
      /* 请求改变数据-用户状态 */
      const { data: res } = await this.$http.put(`users/${userState.id}
      /state/${userState.mg_state}`);/* 写入数据库-后端 */
      if (res.meta.status !== 200) {
        userState.mg_state = !userState.mg_state;
        return this.$message.error('更新用户状态失败!');
      }
      this.$message.success('更新用户状态成功!');
      console.log(userState);
    },
    addUsers: function () {
      this.adddialogVisible = true;
    },
    // 添加对弹框关闭的监听
    closeAddDialog: function () {
      this.$refs.addFormRef.resetFields(); // 关闭列表以后重置表单数据
    },
    closeEditDialog: function () {
      this.$refs.editFormRef.resetFields();// 关闭修改表单初始化监听关闭事件
    },
    addUserdata: function () {
      this.$refs.addFormRef.validate(async valid => { // 数据验证
        if (!valid) return false;
        // 通过验证则可以发起真正的网络请求
        const { data: res } = await this.$http.post('users', this.addForm);
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败');
        }
        this.$message.success('添加成功!');
        this.adddialogVisible = false; // 隐藏列表框
        this.getUserList();
      })
    },
    editUserdata: function () { // 数据验证修改的合法性
      this.$refs.editFormRef.validate(async valid => { // 数据验证
        if (!valid) return false;
        // 通过验证则可以发起真正的网络请求
        const { data: res } = await this.$http.put('users/' + this.editForm.id,
          { email: this.editForm.email, mobile: this.editForm.mobile });
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户失败');
        }
        this.$message.success('更新用户成功!');
        this.editdialogVisible = false; // 隐藏列表框
        this.getUserList();
      })
    },
    /* 展示修改用户信息弹框 */
    showEditDialog: async function (id) {
      // console.log(id);
      const { data: res } = await this.$http.get('users/' + id);
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败');
      }
      this.editForm = res.data;
      this.editdialogVisible = true;
    },
    removeUserByid: async function (id) { // 删除用户信息
      // console.log(id);
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除!');
      }
      const { data: res } = await this.$http.delete('/users/' + id);
      // console.log(res);
      if (res.meta.status !== 200) {
        this.$message.error('删除失败!');
      }
      this.$message.success('删除用户成功!');
      this.getUserList();
    },
    async setRole (userInfo) { // 展示分配角色的对话框
      this.userInfo = userInfo;
      // 获取角色列表
      const { data: res } = await this.$http.get('roles');
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败');
      }
      this.roleLists = res.data; // 进行赋值
      this.setRolesdialogVisible = true;
    },
    async saveRoleInfo () { // 点击按钮分配角色
      if (!this.selectedRoleId) {
        return this.$message.error('请选择一个新的角色！');
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectedRoleId
      })
      if (res.meta.status !== 200) {
        return this.$message.error('修改用户角色失败');
      }
      this.$message.success('修改用户角色成功!');
      this.getUserList();
      this.setRolesdialogVisible = false;
    },
    // 监听分配角色对话框的关闭事件
    setRoleDialogClosed () {
      this.selectedRoleId = '';
      this.userInfo = '';
    }
  }
};
</script>
<style lang="less" scoped>

</style>
